﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Bzzb.Controllers
{
    public class OpLogController : BaseController
    {
        private readonly ILogger<OpLogController> _logger;
        public OpLogController(ILogger<OpLogController> logger, IWebHostEnvironment env, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            string beginTime = string.IsNullOrEmpty(Request.Form["beginTime"]) ? DateTime.Now.ToString("yyyy-MM-dd") : Request.Form["beginTime"];
            string endTime = string.IsNullOrEmpty(Request.Form["endTime"]) ? DateTime.Now.ToString("yyyy-MM-dd") : Request.Form["endTime"];
            _logger.LogInformation($"日志开始时间：{beginTime} 结束时间：{endTime}");
            DynamicFilterInfo dyfilter = JsonConvert.DeserializeObject<DynamicFilterInfo>(@"
{
  'Logic' : 'And',
  'Filters' :
  [
    {
      'Field' : 'Created',
      'Operator' : 'DateRange',
      'Value' : '" + beginTime + ',' + endTime + @"',
    }
  ]
}
");
            List<OpLog> opLogs = await _fsql.Select<OpLog>().WhereDynamicFilter(dyfilter).OrderBy("id desc").Count(out var total).Page(pageIndex, pageSize).ToListAsync();
            _logger.LogInformation("日志查询sql:" + _fsql.Select<OpLog>().WhereDynamicFilter(dyfilter).Page(pageIndex, pageSize).ToSql());
            JObject data = new JObject();
            data.Add("total", total);
            data.Add("list", JArray.FromObject(opLogs));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] OpLog oplog)
        {
            long id = await _fsql.Insert(oplog).ExecuteIdentityAsync();
            oplog.Id = id;
            return RenderJson(data: oplog);
        }
    }
}
